﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using MongoDB.Driver;
using LightSO.ILibrary;
using LightSO.ILibrary.Mapping;

namespace LightSO.Library.MongoDb
{
    /// <summary>
    /// MongoDb上下文对象
    /// </summary>
    /// <typeparam name="T">实体类</typeparam>
    internal class DbContext<T> where T : class
    {
        static readonly object lockObj = new object();
        static Dictionary<string, string> dict = new Dictionary<string, string>();
        static Dictionary<string, DbContext<T>> _instants = new Dictionary<string, DbContext<T>>();

        public MongoDatabase Database { get; set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        public DbContext() : this(DbContext<T>.ConnectionString, false) { }

        public DbContext(bool _slaveOk) : this(DbContext<T>.ConnectionString, _slaveOk) { }

        public DbContext(string _connectionString) : this(_connectionString, false) { }

        public DbContext(string _connectionString, bool _slaveOk) : this(MongoUrl.Create(_connectionString)) { }

        public DbContext(MongoUrl url)
        {
            MongoClient client = new MongoClient(url);
            var server = client.GetServer();
            server.Connect();

            Database = server.GetDatabase(url.DatabaseName);
        }

        /// <summary>
        /// MongoDB中的collection对象
        /// </summary>
        public MongoCollection<T> GetCollection()
        {
            return Database.GetCollection<T>(GetCollectionName());
        }
        /// <summary>
        /// MongoDB中的collection对象
        /// </summary>
        public MongoCollection GetCollection(string name)
        {
            return Database.GetCollection(name);
        }

        public static string GetCollectionName()
        {
            var _att = Attribute.GetCustomAttribute(typeof(T), typeof(CollectionAttribute), true);
            string _collectionName = _att != null ? ((CollectionAttribute)_att).Name : typeof(T).Name;

            if (string.IsNullOrEmpty(_collectionName))
            {
                throw new ArgumentException("Collection name cannot be empty for this entity");
            }
            return _collectionName;
        }

        private static DbContext<T> Create(string connectionName)
        {
            lock (lockObj)
            {
                DbContext<T> _db;
                if (!_instants.TryGetValue(connectionName, out _db))
                {
                    _db = new DbContext<T>(connectionName);
                    _instants.Add(connectionName, _db);
                }
                return _db;
            }

        }
        /// <summary>
        /// 获取数据库连接字符串
        /// </summary>
        private static string ConnectionString
        {
            get
            {
                var classFullName = typeof(T).FullName;
                if (!dict.ContainsKey(classFullName))
                {
                    lock (lockObj)
                    {
                        if (!dict.ContainsKey(classFullName))
                        {
                            var _att = Attribute.GetCustomAttribute(typeof(T), typeof(DBDataSource));
                            var dbName = GetDBName();
                            if (string.IsNullOrWhiteSpace(dbName))
                                dict[classFullName] = ((DBDataSource)_att).ConnectionString;
                            else
                                dict[classFullName] = ((DBDataSource)_att).ConnectionString + "/" + GetDBName();
                        }
                    }
                }

                return dict[classFullName];
            }
        }

        /// <summary>
        /// 获取数据库名称
        /// </summary>
        private static string GetDBName()
        {
            var customAttributes = typeof(T).GetCustomAttributes(false);
            foreach (var item in customAttributes)
            {
                if (item is CollectionAttribute)
                {
                    CollectionAttribute customDataAttribute = item as CollectionAttribute;
                    return customDataAttribute.Name;
                }
            }

            return string.Empty;
        }
    
    }
}
